package com.t309.tzy.interceptors;
import com.t309.tzy.constant.SessionConstant;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 登录拦截器, 可以 拦截 preHandle(handle之前,判断handle要不要执行), 做数据准备
 * handler之前、handler之后、视图渲染之后
 *
 */
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 拦截方法 , 一个简单的拦截器
     * @param request   请求
     * @param response  响应
     * @param handler   处理器
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        boolean flag = true;
        System.out.println("拦截器开始工作");
        //getSession("false")不创建
        //没有session说明没有登录, 执行拦截
        final HttpSession session = request.getSession(false);
        //不要在代码里直接写字面量(字符串等), 减少犯错( 单词写错 ), 方便维护(统一修改)
        if( session == null || StringUtils.isEmpty( session.getAttribute(SessionConstant.USERNAME_IN_SESSION)) ){
            flag = false;
        }else{
            flag = true;
        }
        if(flag){
            //执行后面的handler
            flag = true;
        }else{
            //用户没有登录, 直接跳转到登录页面
            //request.getRequestDispatcher("login").forward(request,response);
            //response.sendRedirect("login");
            return false;
        }
        return flag;
        //return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    /**
     * handler执行之后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 视图渲染之后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }


}
